﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DoNetDrive.Protocol.Door.Door8800.SystemParameter.SN;
using DoNetDrive.Common.Extensions;
using DoNetDrive.Protocol.Door.Door8800.SystemParameter.ConnectPassword;
using DoNetDrive.Protocol.Door.Door8800.SystemParameter.TCPSetting;
using System.Text.RegularExpressions;
using DoNetDrive.Protocol.Door.Door8800.SystemParameter.Deadline;
using DoNetDrive.Protocol.Door.Door8800.SystemParameter.Version;
using DoNetDrive.Protocol.Door.Door8800.SystemParameter.SystemStatus;
using DoNetDrive.Protocol.Door.Door8800.SystemParameter.FunctionParameter;
using System.Collections;
using DoNetDrive.Protocol.Door.Door8800.SystemParameter;
using DoNetDrive.Protocol.Door.Door8800.SystemParameter.Watch;
using DoNetDrive.Protocol.Door.Door8800.SystemParameter.FireAlarm;
using DoNetDrive.Protocol.Door.Door8800.SystemParameter.SmogAlarm;
using DoNetDrive.Protocol.Door.Door8800.SystemParameter.Alarm;
using DoNetDrive.Protocol.Door.Door8800.SystemParameter.WorkStatus;
using DoNetDrive.Protocol.Door.Door8800.SystemParameter.Controller;
using DoNetDrive.Protocol.Door.Door8800.SystemParameter.SearchControltor;
using DoNetDrive.Protocol.OnlineAccess;
using DoNetDrive.Protocol.Door.Door8800.SystemParameter.CacheContent;
using DoNetDrive.Protocol.Door.Door8800.SystemParameter.KeepAliveInterval;
using DoNetDrive.Protocol.Door.Door8800.SystemParameter.TheftFortify;
using DoNetDrive.Protocol.Door.Door8800.SystemParameter.BalcklistAlarmOption;
using DoNetDrive.Protocol.Door.Door8800.SystemParameter.ExploreLockMode;
using DoNetDrive.Protocol.Door.Door8800.SystemParameter.Check485Line;
using DoNetDrive.Protocol.Door.Door8800.SystemParameter.TCPClient;
using DoNetDrive.Protocol.Door.Door8800.SystemParameter.CardDeadlineTipDay;
using DoNetDrive.Protocol.Door.Door8800.SystemParameter.ControlPanelTamperAlarm;
using DoNetDrive.Protocol.Door.Door8800.SystemParameter.HTTPPageLandingSwitch;
using DoNetDrive.Protocol.Door.Door8800.SystemParameter.LawfulCardReleaseAlarmSwitch;
using DoNetDrive.Protocol.Door.Test.TCPPublisher;
using DoNetDrive.Core.Command;

namespace DoNetDrive.Protocol.Door.Test
{

    public partial class frmSystem : frmNodeForm
    {
        #region 单例模式
        private static object lockobj = new object();
        private static frmSystem onlyObj;

        private TCPDetailIObserver TCPIObserver = new TCPDetailIObserver();
        public static frmSystem GetForm(INMain main)
        {
            if (onlyObj == null)
            {
                lock (lockobj)
                {
                    if (onlyObj == null)
                    {
                        onlyObj = new frmSystem(main);
                        frmMain.AddNodeForms(onlyObj);
                    }
                }
            }
            return onlyObj;
        }

        private frmSystem(INMain main) : base(main)
        {
            InitializeComponent();

            TCPIObserver.Subscribe(frmMain.TCPIObservable);
            TCPIObserver.ValueChanged += TCPIObserver_ValueChanged;
        }

        private void TCPIObserver_ValueChanged(TCPDetail tcp)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action(() => TCPIObserver_ValueChanged(tcp)));
                return;
            }
            if (tcp != null)
            {
                txtIP.Text = tcp.mIP;
                txtTCPPort.Text = tcp.mTCPPort.ToString();
                Btn_EditTCPIP.Enabled = true;
            }
            else
            {
                Btn_EditTCPIP.Enabled = false;
            }
        }
        #endregion

        private void frmSystem_Load(object sender, EventArgs e)
        {
            TCPIObserver_ValueChanged(frmMain.SelectedTCPDetail);
            LoadUILanguage();
        }

        public override void LoadUILanguage()
        {
            base.LoadUILanguage();
            //设备参数设置
            GetLanguage(tabSysParameterPage);
            var read = GetLanguage("Read");
            var write = GetLanguage("Write");
            GetLanguage(gbPassword);
            GetLanguage(Lab_ConnectPassword);
            GetLanguage(butResetConnectPassword);
            GetLanguage(gbRunParameters);
            GetLanguage(Lab_Deadline);
            GetLanguage(Lab_DeanlineDay);
            GetLanguage(Lab_Version);
            GetLanguage(gbTCP);
            GetLanguage(gpDeviceRunInfo);
            GetLanguage(Lab_RunDay);
            GetLanguage(Lab_RestartCount);
            GetLanguage(Lab_Temperature);
            GetLanguage(Lab_StartTime);
            GetLanguage(Lab_FormatCount);
            GetLanguage(Lab_UPS);
            GetLanguage(Lab_Voltage);
            GetLanguage(gpWatch);
            GetLanguage(Lab_WatchStatus);
            lbWatchState.Text = GetLanguage("lbWatchState_1");
            GetLanguage(btnBeginWatch);
            GetLanguage(btnCloseWatch);
            GetLanguage(btnReadWatchState);
            GetLanguage(gp_Cache);
            GetLanguage(Lab_CacheContent);
            GetLanguage(gpTcpClientModel);
            GetLanguage(Lab_KeepAliveInterval1);
            GetLanguage(Lab_KeepAliveInterval2);
            GetLanguage(btnInitalData);

            butReadSN.Text = read;
            butReadConnectPassword.Text = read;
            btnReadVersion.Text = read;
            btnReadDeadline.Text = read;
            btnReadSystemStatus.Text = read;
            butRendTCPSetting.Text = read;
            btnReadCacheContent.Text = read;
            btnReadKeepAliveInterval.Text = read;

            butWriteSN.Text = write;
            butWriteConnectPassword.Text = write;
            btnWriteDeadline.Text = write;
            butWriteTCPSetting.Text = write;
            btnWriteCacheContent.Text = write;
            btnWriteKeepAliveInterval.Text = write;
            //扩展功能
            GetLanguage(tabPage3);
            GetLanguage(groupBox14);
            GetLanguage(groupBox15);
            GetLanguage(groupBox17);
            GetLanguage(Lab_ardDeadlineTipDay);
            GetLanguage(groupBox19);
            var nonuse = GetLanguage("nonuse");
            var use = GetLanguage("use");
            label72.Text = GetLanguage("Lab_DeanlineDay");
            rBtnNoExploreLockMode.Text = nonuse;
            rBtnNoCheck485Line.Text = nonuse;
            rBtnNoHTTPPageLandingSwitch.Text = nonuse;

            rBtnExploreLockMode.Text = use;
            rBtnCheck485Line.Text = use;
            rBtnHTTPPageLandingSwitch.Text = use;
            btnReadExploreLockMode.Text = read;
            btnReadCheck485Line.Text = read;
            btnReadCardDeadlineTipDay.Text = read;
            btnReadHTTPPageLandingSwitch.Text = read;

            btnWriteExploreLockMode.Text = write;
            btnWriteCheck485Line.Text = write;
            btnWriteCardDeadlineTipDay.Text = write;
            btnWriteHTTPPageLandingSwitch.Text = write;

            //设备状态信息
            GetLanguage(tabPage1);
            GetLanguage(groupBox9);
            GetLanguage(dgvEquipmentStatusInfo);
            GetLanguage(label66);
            GetLanguage(label65);
            GetLanguage(btnWorkStatusInfo);
            GetLanguage(groupBox16);
            GetLanguage(dgvTCPClientList);
            GetLanguage(btnReadTCPClientList);
            GetLanguage(btnStopTCPClientConnection);
            GetLanguage(btnStopAllTCPClientConnection);
            lbSWatchState.Text = GetLanguage("lbWatchState_1");
            //功能参数
            GetLanguage(label20);
            GetLanguage(rBtnCover);
            GetLanguage(rBtnNoCover);
            GetLanguage(label21);
            GetLanguage(label22);
            GetLanguage(label34);
            GetLanguage(label33);
            GetLanguage(label35);
            GetLanguage(groupBox4);
            GetLanguage(label42);
            GetLanguage(label37);
            GetLanguage(groupBox7);
            GetLanguage(label58);
            GetLanguage(label59);
            GetLanguage(rBtnPayRent);
            GetLanguage(rBtnPayManagementFee);
            GetLanguage(label61);
            GetLanguage(label60);
            GetLanguage(rBtnEnableValidation);
            GetLanguage(Btn_EditTCPIP);
            GetLanguage(Lab_Ip);
            GetLanguage(Lab_TCPPort);

            //读取
            btnReadRecordMode.Text = read;
            btnReadKeyboard.Text = read;
            btnReadLockInteraction.Text = read;
            btnReadBroadcast.Text = read;
            btnReadReaderCheckMode.Text = read;
            btnReadBuzzer.Text = read;
            btnReadEnterDoorLimit.Text = read;
            btnReadReadCardSpeak.Text = read;
            //写入
            btnWriteRecordMode.Text = write;
            btnWriteKeyboard.Text = write;
            btnWirteLockInteraction.Text = write;
            btnWriteBroadcast.Text = write;
            btnWriteReaderCheckMode.Text = write;
            btnWriteBuzzer.Text = write;
            btnWriteEnterDoorLimit.Text = write;
            btnWriteReadCardSpeak.Text = write;

            var door = GetLanguage("Door");
            cBoxDoor1.Text = door + 1;
            cBoxDoor2.Text = door + 2;
            cBoxDoor3.Text = door + 3;
            cBoxDoor4.Text = door + 4;



            rBtnNoEnable.Text = nonuse;
            rBtnNoBuzzer.Text = nonuse;
            rBtnNoEnableReadCardSpeak.Text = nonuse;

            rBtnEnable.Text = use;
            rBtnBuzzer.Text = use;
            rBtnEnableReadCardSpeak.Text = use;
            var enter = GetLanguage("Enter");
            var limit = GetLanguage("Limit");

            label45.Text = 2 + enter;
            label46.Text = 1 + enter;
            label44.Text = 3 + enter;
            label43.Text = 4 + enter;

            label41.Text = 1 + limit;
            label40.Text = 2 + limit;
            label39.Text = 3 + limit;
            label38.Text = 4 + limit;

            #region 获取设备状态信息
            this.dgvEquipmentStatusInfo.Rows.Add(9);
            this.dgvEquipmentStatusInfo.Rows[0].Cells[0].Value = door + "1";
            this.dgvEquipmentStatusInfo.Rows[1].Cells[0].Value = door + "2";
            this.dgvEquipmentStatusInfo.Rows[2].Cells[0].Value = door + "3";
            this.dgvEquipmentStatusInfo.Rows[3].Cells[0].Value = door + "4";
            this.dgvEquipmentStatusInfo.Rows[4].Cells[0].Value = GetLanguage("dgvAlarmType10"); //"消防报警";
            this.dgvEquipmentStatusInfo.Rows[5].Cells[0].Value = GetLanguage("dgvAlarmType8");// "匪警报警";
            this.dgvEquipmentStatusInfo.Rows[6].Cells[0].Value = GetLanguage("dgvAlarmType11");// "烟雾报警";
            this.dgvEquipmentStatusInfo.Rows[7].Cells[0].Value = GetLanguage("dgvAlarmType9");// "防盗主机";
            this.dgvEquipmentStatusInfo.Rows[8].Cells[0].Value = GetLanguage("dgvAlarmType13"); //"防拆报警";
            this.dgvEquipmentStatusInfo.AllowUserToAddRows = false;
            #endregion
            SetControlsFont(this.Controls, GetLanguageFont());
        }

        #region SN的读写操作

        private void butReadSN_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ReadSN cmd = new ReadSN(cmdDtl);
            mMainForm.AddCommand(cmd);

            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                SN_Result result = cmde.Command.getResult() as SN_Result;
                string sn = result.SNBuf.GetString();
                Invoke(() =>
                {
                    txtSN.Text = sn;
                });
                mMainForm.AddCmdLog(cmde, sn);
            };
        }

        private bool CheckSN()
        {
            string sn = txtSN.Text;
            if (sn.Length != 16)
            {
                MsgErr($"{GetLanguage("Msg1")}！");
                return false;
            }
            int len = System.Text.Encoding.ASCII.GetByteCount(sn);
            if (len != 16)
            {
                MsgErr($"{GetLanguage("Msg1")}！");
                return false;
            }
            return true;
        }

        private void butWriteSN_Click(object sender, EventArgs e)
        {
            if (!CheckSN()) return;
            string sn = txtSN.Text;

            INCommand cmd;
            if (mMainForm.IsBroadcast())
            {
                var msg = GetLanguage("Msg170") + txtSN.Text + Environment.NewLine + GetLanguage("Msg171");
                var tooltip = GetLanguage("Msg172");
                if (MessageBox.Show(msg, tooltip, MessageBoxButtons.YesNo) == DialogResult.No)
                {
                    return;
                }
                var cmdDtl = mMainForm.GetUDPCommandDetail();
                if (cmdDtl == null) return;
                cmd = new WriteSN_Broadcast(cmdDtl, new SN_Parameter(sn));
            }
            else
            {
                var cmdDtl = mMainForm.GetCommandDetail();
                if (cmdDtl == null) return;
                cmd = new WriteSN(cmdDtl, new SN_Parameter(sn));
            }
            mMainForm.AddCommand(cmd);
        }
        #endregion

        #region 通讯密码
        private void butReadConnectPassword_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ReadConnectPassword cmd = new ReadConnectPassword(cmdDtl);
            mMainForm.AddCommand(cmd);

            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                Password_Result result = cmde.Command.getResult() as Password_Result;
                string pwd = result.Password;
                Invoke(() =>
                {
                    txtConnectPassword.Text = pwd;
                });
                mMainForm.AddCmdLog(cmde, pwd);
            };
        }

        private void butWriteConnectPassword_Click(object sender, EventArgs e)
        {
            string pwd = txtConnectPassword.Text;
            if (pwd.Length != 8)
            {
                MsgErr($"{GetLanguage("Msg2")}！");
                return;
            }
            if (!pwd.IsHex())
            {
                MsgErr($"{GetLanguage("Msg2")}！");
                return;
            }


            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            WriteConnectPassword cmd = new WriteConnectPassword(cmdDtl, new Password_Parameter(pwd));
            mMainForm.AddCommand(cmd);


        }

        private void butResetConnectPassword_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ResetConnectPassword cmd = new ResetConnectPassword(cmdDtl);
            mMainForm.AddCommand(cmd);

        }
        #endregion

        #region TCP参数
        private void ButRendTCPSetting_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ReadTCPSetting cmd = new ReadTCPSetting(cmdDtl);
            mMainForm.AddCommand(cmd);

            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                ReadTCPSetting_Result result = cmde.Command.getResult() as ReadTCPSetting_Result;
                string TCPInfo = DebugTCPDetail(result.TCP);
                mMainForm.AddCmdLog(cmde, TCPInfo);
                frmMain.TCPIObservable.Publish(result.TCP);
            };
        }

        private string DebugTCPDetail(TCPDetail tcp)
        {
            string MAC = tcp.mMAC; //MAC地址
            string IP = tcp.mIP; //IP
            string IPMask = tcp.mIPMask; //子网掩码
            string IPGateway = tcp.mIPGateway; //网关地址
            string DNS = tcp.mDNS; //DNS
            string DNSBackup = tcp.mDNSBackup; //备用DNS
            string TCPPort = tcp.mTCPPort.ToString(); //本地TCP端口
            string UDPPort = tcp.mUDPPort.ToString(); //本地UDP端口
            string ServerIP = tcp.mServerIP; //服务器IP
            string ServerAddr = tcp.mServerAddr; //服务器域名
            string ServerPort = tcp.mServerPort.ToString(); //服务器端口

            int ProtocolType = tcp.mProtocolType; //TCP工作模式
            bool AutoIP = tcp.mAutoIP; //是否自动获得IP

            var TCPInfo = new StringBuilder();
            TCPInfo.AppendLine($"{GetLanguage("Lab_MAC")}{MAC}");
            TCPInfo.AppendLine($"IP:{IP}");
            TCPInfo.AppendLine($"{GetLanguage("Lab_IPMask")}{IPMask}");
            TCPInfo.AppendLine($"{GetLanguage("Lab_IPGateway")}{IPGateway}");
            TCPInfo.AppendLine($"DNS:{DNS}");
            TCPInfo.AppendLine($"{GetLanguage("Lab_DNSBackup")}{DNSBackup}");
            TCPInfo.AppendLine($"{GetLanguage("Lab_TCPPort")}{TCPPort}");
            TCPInfo.AppendLine($"{GetLanguage("Lab_UDPPort")}{UDPPort}");
            TCPInfo.AppendLine($"{GetLanguage("Lab_ServerIP")}{ServerIP}");
            TCPInfo.AppendLine($"{GetLanguage("Lab_ServerAddr")}{ServerAddr}");
            TCPInfo.AppendLine($"{GetLanguage("Lab_ServerPort")}{ServerPort}");
            return TCPInfo.ToString();
        }

        private void ButWriteTCPSetting_Click(object sender, EventArgs e)
        {
            if (!TCPDetail.CheckIP(txtIP.Text.Trim()))
            {
                MsgErr($"{GetLanguage("Msg4")}！");
                return;
            }
            var tcpPort = Convert.ToInt32(txtTCPPort.Text.Trim());
            if (tcpPort > 65535 || tcpPort <= 0)
            {
                MsgErr($"{GetLanguage("Msg10")}！");
                return;
            }
            var tcpDtl = frmMain.SelectedTCPDetail;
            TCPDetail tcp = new TCPDetail
            {
                mIP = txtIP.Text.Trim(),
                mMAC = tcpDtl.mMAC,
                mIPMask = tcpDtl.mIPMask,
                mIPGateway = tcpDtl.mIPGateway,
                mDNS = tcpDtl.mDNS,
                mDNSBackup = tcpDtl.mDNSBackup,
                mTCPPort = tcpPort,
                mUDPPort = tcpDtl.mUDPPort,
                mServerIP = tcpDtl.mServerIP,
                mServerAddr = tcpDtl.mServerAddr,
                mServerPort = tcpDtl.mServerPort
            };
            WriteTCP(tcp);
        }

        /// <summary>
        /// 编辑TCP参数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_EditTCPIP_Click(object sender, EventArgs e)
        {
            TCPDetailForm frm = new TCPDetailForm(mMainForm);
            frm.TCPChanged += WriteTCP;
            frm.ShowDialog();
        }
        /// <summary>
        /// 写入TCP参数
        /// </summary>
        /// <param name="tcp"></param>
        private void WriteTCP(TCPDetail tcp)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            WriteTCPSetting cmd = new WriteTCPSetting(cmdDtl, new WriteTCPSetting_Parameter(tcp));
            mMainForm.AddCommand(cmd);
            cmdDtl.CommandCompleteEvent += (s, e) =>
            {
                frmMain.TCPIObservable.Publish(tcp);
            };
        }
        #endregion

        #region 设备有效期
        private void BtnReadDeadline_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ReadDeadline cmd = new ReadDeadline(cmdDtl);
            mMainForm.AddCommand(cmd);

            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                ReadDeadline_Result result = cmde.Command.getResult() as ReadDeadline_Result;

                ushort Deadline = result.Deadline; //有效期
                string DeadlineInfo = string.Empty;
                if (Deadline == 0)
                {
                    DeadlineInfo = GetLanguage("Msg25");
                }
                else if (Deadline == 65535)
                {
                    DeadlineInfo = GetLanguage("Msg26");
                }
                else
                {
                    DeadlineInfo = Deadline.ToString() + GetLanguage("Msg27"); ;
                }

                Invoke(() =>
                {
                    cbxDeadline.Text = DeadlineInfo.Replace(GetLanguage("Msg27"), "");
                });
                string DeadlineDay = GetLanguage("Msg28") + ":" + DeadlineInfo;
                mMainForm.AddCmdLog(cmde, DeadlineDay);
            };
        }

        private void BtnWriteDeadline_Click(object sender, EventArgs e)
        {
            string reg = @"^\+?[0-9]*$";
            if (!Regex.IsMatch(cbxDeadline.Text.Trim(), reg))
            {
                if (cbxDeadline.Text != GetLanguage("Msg26") && cbxDeadline.Text != GetLanguage("Msg25"))
                {
                    MsgErr(GetLanguage("Msg29") + "！");
                    return;
                }
            }
            if (Regex.IsMatch(cbxDeadline.Text.Trim(), reg))
            {
                if (Convert.ToUInt32(cbxDeadline.Text) < 0 || Convert.ToUInt32(cbxDeadline.Text) > 65535)
                {
                    MsgErr(GetLanguage("Msg29") + "！");
                    return;
                }
            }

            ushort deadlineDay = 0;
            string deadlineInfo = cbxDeadline.Text;
            if (deadlineInfo == GetLanguage("Msg26"))
            {
                deadlineDay = 65535;
            }
            else if (deadlineInfo == GetLanguage("Msg27"))
            {
                deadlineDay = 0;
            }
            else
            {
                deadlineDay = Convert.ToUInt16(cbxDeadline.Text);
            }

            //WriteDeadline_Parameter wp = new WriteDeadline_Parameter();
            //wp.Deadline = deadlineDay;
            //var buf = DotNetty.Buffers.UnpooledByteBufferAllocator.Default.Buffer(0x02);
            //wp.GetBytes(buf);

            //WriteDeadline_Parameter wp2 = new WriteDeadline_Parameter();
            //wp2.SetBytes(buf);

            //string DeadlineDay = "设备剩余有效期天数:" + deadlineDay;
            //mMainForm.AddCmdLog(null, DeadlineDay);

            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            WriteDeadline cmd = new WriteDeadline(cmdDtl, new WriteDeadline_Parameter(deadlineDay));
            mMainForm.AddCommand(cmd);
        }
        #endregion

        #region 设备版本号
        private void BtnReadVersion_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ReadVersion cmd = new ReadVersion(cmdDtl);
            mMainForm.AddCommand(cmd);

            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                ReadVersion_Result result = cmde.Command.getResult() as ReadVersion_Result;
                string version = result.Version.ToString();
                Invoke(() =>
                {
                    txtVersion.Text = "Ver " + version;
                });
                version = GetLanguage("Msg20") + version;
                mMainForm.AddCmdLog(cmde, version);
            };
        }
        #endregion

        #region 设备运行信息
        private void BtnReadSystemStatus_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ReadSystemStatus cmd = new ReadSystemStatus(cmdDtl);
            mMainForm.AddCommand(cmd);

            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                ReadSystemStatus_Result result = cmde.Command.getResult() as ReadSystemStatus_Result;
                string RunDay = result.RunDay.ToString() + GetLanguage("Msg27"); //设备已运行天数
                string FormatCount = result.FormatCount.ToString() + GetLanguage("Msg30"); //格式化次数
                string RestartCount = result.RestartCount.ToString() + GetLanguage("Msg30"); //看门狗复位次数
                string UPS = result.UPS == 0 ? GetLanguage("Msg31") : GetLanguage("Msg32"); //UPS工作状态
                string Temperature = result.Temperature; //设备温度
                string Voltage = result.Voltage; //接入电压
                string StartTime = result.StartTime; //上电时间

                Invoke(() =>
                {
                    txtRunDay.Text = RunDay;
                    txtFormatCount.Text = FormatCount;
                    txtRestartCount.Text = RestartCount;
                    txtUPS.Text = UPS;
                    txtTemperature.Text = Temperature;
                    txtVoltage.Text = Voltage;
                    txtStartTime.Text = StartTime;

                });
                string TCPInfo = GetLanguage("Lab_RunDay") + RunDay + Environment.NewLine +
                                 GetLanguage("Lab_FormatCount") + FormatCount + Environment.NewLine +
                                 GetLanguage("Lab_RestartCount") + RestartCount + Environment.NewLine +
                                GetLanguage("Lab_UPS") + UPS + Environment.NewLine +
                                 GetLanguage("Lab_Temperature") + Temperature + Environment.NewLine +
                                 GetLanguage("Lab_Voltage") + Voltage + Environment.NewLine +
                                GetLanguage("Lab_StartTime") + StartTime;
                mMainForm.AddCmdLog(cmde, TCPInfo);
            };
        }
        #endregion

        #region 记录存储方式
        private void BtnReadRecordMode_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ReadRecordMode cmd = new ReadRecordMode(cmdDtl);
            mMainForm.AddCommand(cmd);

            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                ReadRecordMode_Result result = cmde.Command.getResult() as ReadRecordMode_Result;
                string ModeStr = result.Mode == 0 ? GetLanguage("Msg33") : GetLanguage("Msg34"); //记录存储方式
                Invoke(() =>
                {
                    if (result.Mode == 0)
                    {
                        rBtnCover.Checked = true;
                    }
                    else
                    {
                        rBtnNoCover.Checked = true;
                    }
                });
                ModeStr = GetLanguage("Msg12") + ModeStr;
                mMainForm.AddCmdLog(cmde, ModeStr);
            };
        }

        private void BtnWriteRecordMode_Click(object sender, EventArgs e)
        {
            byte mode = 0;
            if (rBtnNoCover.Checked == true)
            {
                mode = 1;
            }

            //WriteRecordMode_Parameter wp = new WriteRecordMode_Parameter();
            //wp.Mode = mode;
            //var buf = DotNetty.Buffers.UnpooledByteBufferAllocator.Default.Buffer(0x02);
            //wp.GetBytes(buf);

            //WriteRecordMode_Parameter wp2 = new WriteRecordMode_Parameter();
            //wp2.SetBytes(buf);

            //string DeadlineDay = "记录存储方式:" + mode;
            //mMainForm.AddCmdLog(null, DeadlineDay);

            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            WriteRecordMode cmd = new WriteRecordMode(cmdDtl, new WriteRecordMode_Parameter(mode));
            mMainForm.AddCommand(cmd);
        }
        #endregion

        #region 读卡器密码键盘启用功能开关
        private void BtnReadKeyboard_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ReadKeyboard cmd = new ReadKeyboard(cmdDtl);
            mMainForm.AddCommand(cmd);

            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                ReadKeyboard_Result result = cmde.Command.getResult() as ReadKeyboard_Result;
                string KeyboardInfo = string.Empty;
                Invoke(() =>
                {
                    for (int i = 0; i < result.Keyboard.Count; i++)
                    {
                        if (result.Keyboard[i] == true)
                        {
                            if (i == 0)
                            {
                                cBox1.Checked = true;
                            }
                            else if (i == 1)
                            {
                                cBox2.Checked = true;
                            }
                            else if (i == 2)
                            {
                                cBox3.Checked = true;
                            }
                            else if (i == 3)
                            {
                                cBox4.Checked = true;
                            }
                            else if (i == 4)
                            {
                                cBox5.Checked = true;
                            }
                            else if (i == 5)
                            {
                                cBox6.Checked = true;
                            }
                            else if (i == 6)
                            {
                                cBox7.Checked = true;
                            }
                            else if (i == 7)
                            {
                                cBox8.Checked = true;
                            }

                            KeyboardInfo = KeyboardInfo + $"  {GetLanguage("Msg35")}：" + (i + 1) + "，" + GetLanguage("Msg36") + Environment.NewLine;
                        }
                        else
                        {
                            KeyboardInfo = KeyboardInfo + $"  {GetLanguage("Msg35")}：" + (i + 1) + "，" + GetLanguage("Msg37") + Environment.NewLine;
                        }
                    }
                });
                mMainForm.AddCmdLog(cmde, KeyboardInfo);
            };
        }

        private void BtnWriteKeyboard_Click(object sender, EventArgs e)
        {
            BitArray bitSet = new BitArray(8);
            bitSet[0] = cBox1.Checked;
            bitSet[1] = cBox2.Checked;
            bitSet[2] = cBox3.Checked;
            bitSet[3] = cBox4.Checked;
            bitSet[4] = cBox5.Checked;
            bitSet[5] = cBox6.Checked;
            bitSet[6] = cBox7.Checked;
            bitSet[7] = cBox8.Checked;
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            WriteKeyboard cmd = new WriteKeyboard(cmdDtl, new WriteKeyboard_Parameter(bitSet));
            mMainForm.AddCommand(cmd);
        }
        #endregion

        #region 互锁参数
        private void BtnReadLockInteraction_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ReadLockInteraction cmd = new ReadLockInteraction(cmdDtl);
            mMainForm.AddCommand(cmd);

            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                ReadLockInteraction_Result result = cmde.Command.getResult() as ReadLockInteraction_Result;
                string DoorLockInfo = string.Empty;
                Invoke(() =>
                {
                    for (int i = 0; i < result.DoorPort.DoorMax; i++)
                    {
                        if (result.DoorPort.DoorPort[i] == 1)
                        {
                            if (i == 0)
                            {
                                cBoxDoor1.Checked = true;
                            }
                            else if (i == 1)
                            {
                                cBoxDoor2.Checked = true;
                            }
                            else if (i == 2)
                            {
                                cBoxDoor3.Checked = true;
                            }
                            else if (i == 3)
                            {
                                cBoxDoor4.Checked = true;
                            }

                            DoorLockInfo = DoorLockInfo + "  " + GetLanguage("Door") + (i + 1) + " :" + GetLanguage("Msg38") + Environment.NewLine;
                        }
                        if (string.IsNullOrWhiteSpace(DoorLockInfo))
                        {
                            DoorLockInfo = GetLanguage("Msg39");
                        }
                    }
                });
                mMainForm.AddCmdLog(cmde, DoorLockInfo);
            };
        }

        private void BtnWirteLockInteraction_Click(object sender, EventArgs e)
        {
            DoorPortDetail dpd = new DoorPortDetail(4);
            if (cBoxDoor1.Checked)
            {
                dpd.DoorPort[0] = 1;
            }
            else
            {
                dpd.DoorPort[0] = 0;
            }
            if (cBoxDoor2.Checked)
            {
                dpd.DoorPort[1] = 1;
            }
            else
            {
                dpd.DoorPort[1] = 0;
            }
            if (cBoxDoor3.Checked)
            {
                dpd.DoorPort[2] = 1;
            }
            else
            {
                dpd.DoorPort[2] = 0;
            }
            if (cBoxDoor4.Checked)
            {
                dpd.DoorPort[3] = 1;
            }
            else
            {
                dpd.DoorPort[3] = 0;
            }

            //WriteLockInteraction_Parameter wp = new WriteLockInteraction_Parameter();
            //wp.DoorPort = dpd;
            //var buf = DotNetty.Buffers.UnpooledByteBufferAllocator.Default.Buffer(0x02);
            //wp.GetBytes(buf);

            //WriteLockInteraction_Parameter wp2 = new WriteLockInteraction_Parameter();
            //wp2.SetBytes(buf);

            //string DeadlineDay = "门1:" + dpd.DoorPort[0] +
            //                     "  门2:" + dpd.DoorPort[1] +
            //                     "  门3:" + dpd.DoorPort[2] +
            //                     "  门4:" + dpd.DoorPort[3];
            //mMainForm.AddCmdLog(null, DeadlineDay);

            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            WriteLockInteraction cmd = new WriteLockInteraction(cmdDtl, new WriteLockInteraction_Parameter(dpd));
            mMainForm.AddCommand(cmd);
        }
        #endregion

        #region 语音播报语音段开关
        private void BtnReadBroadcast_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ReadBroadcast cmd = new ReadBroadcast(cmdDtl);
            mMainForm.AddCommand(cmd);

            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                ReadBroadcast_Result result = cmde.Command.getResult() as ReadBroadcast_Result;

                Invoke(() =>
                {
                    byte[] broadcast = new byte[4];
                    Array.Copy(result.Broadcast.Broadcast, 6, broadcast, 0, 4);
                    StringBuilder BroadcastInfo = new StringBuilder(64); //语音段开关

                    Array.Reverse(broadcast);
                    BitArray bit = new BitArray(broadcast);
                    for (int i = 30; i >= 0; i--)
                    {
                        BroadcastInfo.Append(bit[i] ? 1 : 0);
                    }

                    txtBroadcast.Text = BroadcastInfo.ToString();
                    string IntervalTimeStr = GetLanguage("Msg60") + "：" + txtBroadcast.Text + $"  {GetLanguage("Msg61")} 31←1";
                    mMainForm.AddCmdLog(cmde, IntervalTimeStr);
                });

            };
        }

        private void BtnWriteBroadcast_Click(object sender, EventArgs e)
        {
            string reg = @"^\+?[0-1]*$";
            if (!Regex.IsMatch(txtBroadcast.Text.Trim(), reg) || txtBroadcast.Text.Trim().Length != 31)
            {
                MsgErr(GetLanguage("Msg62") + "！");
                return;
            }
            byte[] bData = new byte[10];

            string strBit = txtBroadcast.Text.Trim();
            strBit = "0" + strBit;

            byte[] tmpData = new byte[4];
            BitArray bit = new BitArray(tmpData);
            int strIndex = 0;
            for (int i = 30; i >= 0; i--)
            {
                bit[i] = (strBit.Substring(++strIndex, 1) == "1");
            }

            bit.CopyTo(tmpData, 0);
            Array.Reverse(tmpData);
            Array.Copy(tmpData, 0, bData, 6, 4);

            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            WriteBroadcast cmd = new WriteBroadcast(cmdDtl, new WriteBroadcast_Parameter(bData));
            mMainForm.AddCommand(cmd);
        }
        #endregion

        #region 读卡器数据校验
        private void BtnReadReaderCheckMode_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ReadReaderCheckMode cmd = new ReadReaderCheckMode(cmdDtl);
            mMainForm.AddCommand(cmd);

            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                ReadReaderCheckMode_Result result = cmde.Command.getResult() as ReadReaderCheckMode_Result;
                string ModeStr = string.Empty; //读卡器数据校验
                Invoke(() =>
                {
                    if (result.ReaderCheckMode == 0)
                    {
                        rBtnNoEnable.Checked = true;
                        ModeStr = GetLanguage("Msg63");
                    }
                    else if (result.ReaderCheckMode == 1)
                    {
                        rBtnEnable.Checked = true;
                        ModeStr = GetLanguage("Msg64");
                    }
                    else
                    {
                        rBtnEnableValidation.Checked = true;
                        ModeStr = GetLanguage("Msg65");
                    }
                });
                ModeStr = GetLanguage("Msg66") + "：" + ModeStr;
                mMainForm.AddCmdLog(cmde, ModeStr);
            };
        }

        private void BtnWriteReaderCheckMode_Click(object sender, EventArgs e)
        {
            byte mode = 0;
            if (rBtnEnable.Checked == true)
            {
                mode = 1;
            }
            else if (rBtnEnableValidation.Checked == true)
            {
                mode = 2;
            }

            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            WriteReaderCheckMode cmd = new WriteReaderCheckMode(cmdDtl, new WriteReaderCheckMode_Parameter(mode));
            mMainForm.AddCommand(cmd);
        }
        #endregion

        #region 主板蜂鸣器
        private void BtnReadBuzzer_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ReadBuzzer cmd = new ReadBuzzer(cmdDtl);
            mMainForm.AddCommand(cmd);

            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                ReadBuzzer_Result result = cmde.Command.getResult() as ReadBuzzer_Result;
                string ModeStr = result.Buzzer == 0 ? GetLanguage("Msg97") : GetLanguage("Msg98"); //记录存储方式
                Invoke(() =>
                {
                    if (result.Buzzer == 0)
                    {
                        rBtnNoBuzzer.Checked = true;
                    }
                    else
                    {
                        rBtnBuzzer.Checked = true;
                    }
                });
                ModeStr = GetLanguage("Msg67") + "：" + ModeStr;
                mMainForm.AddCmdLog(cmde, ModeStr);
            };
        }

        private void BtnWriteBuzzer_Click(object sender, EventArgs e)
        {
            byte buzzer = 0;
            if (rBtnBuzzer.Checked == true)
            {
                buzzer = 1;
            }

            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            WriteBuzzer cmd = new WriteBuzzer(cmdDtl, new WriteBuzzer_Parameter(buzzer));
            mMainForm.AddCommand(cmd);
        }
        #endregion

        #region 门内人数限制
        private void BtnReadEnterDoorLimit_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ReadEnterDoorLimit cmd = new ReadEnterDoorLimit(cmdDtl);
            mMainForm.AddCommand(cmd);

            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                ReadEnterDoorLimit_Result result = cmde.Command.getResult() as ReadEnterDoorLimit_Result;
                string GlobalLimit = result.Limit.GlobalLimit.ToString(); //全局上限
                string Door1Limit = result.Limit.DoorLimitArray[0].ToString(); //1号门上限
                string Door2Limit = result.Limit.DoorLimitArray[1].ToString(); //2号门上限
                string Door3Limit = result.Limit.DoorLimitArray[2].ToString(); //3号门上限
                string Door4Limit = result.Limit.DoorLimitArray[3].ToString(); //4号门上限

                string GlobalEnter = result.Limit.GlobalEnter.ToString(); //全局人数
                string Door1Enter = result.Limit.DoorEnterArray[0].ToString(); //1号门人数
                string Door2Enter = result.Limit.DoorEnterArray[1].ToString(); //2号门人数
                string Door3Enter = result.Limit.DoorEnterArray[2].ToString(); //3号门人数
                string Door4Enter = result.Limit.DoorEnterArray[3].ToString(); //4号门人数
                Invoke(() =>
                {
                    txtGlobalLimit.Text = GlobalLimit;
                    txtDoor1Limit.Text = Door1Limit;
                    txtDoor2Limit.Text = Door2Limit;
                    txtDoor3Limit.Text = Door3Limit;
                    txtDoor4Limit.Text = Door4Limit;

                    txtGlobalEnter.Text = GlobalEnter;
                    txtDoor1Enter.Text = Door1Enter;
                    txtDoor2Enter.Text = Door2Enter;
                    txtDoor3Enter.Text = Door3Enter;
                    txtDoor4Enter.Text = Door4Enter;

                });
                string EnterDoorLimitInfo = GetLanguage("label42") + GlobalLimit + Environment.NewLine +
                                 $"  1{GetLanguage("Limit")}：" + Door1Limit + Environment.NewLine +
                                 $"  2{GetLanguage("Limit")}：" + Door2Limit + Environment.NewLine +
                                 $"  3{GetLanguage("Limit")}：" + Door3Limit + Environment.NewLine +
                                 $"  4{GetLanguage("Limit")}：" + Door4Limit + Environment.NewLine +
                                 GetLanguage("label37") + GlobalEnter + Environment.NewLine +
                                 $"  1{GetLanguage("Enter")}：" + Door1Enter + Environment.NewLine +
                                 $"  2{GetLanguage("Enter")}：" + Door2Enter + Environment.NewLine +
                                 $"  3{GetLanguage("Enter")}：" + Door3Enter + Environment.NewLine +
                                 $"  4{GetLanguage("Enter")}：" + Door4Enter;
                mMainForm.AddCmdLog(cmde, EnterDoorLimitInfo);
            };
        }

        private void BtnWriteEnterDoorLimit_Click(object sender, EventArgs e)
        {
            string reg = @"^\+?[0-9]*$";
            UInt32 ui32 = 0;
            if (!Regex.IsMatch(txtGlobalLimit.Text.Trim(), reg))
            {
                MsgErr(GetLanguage("Msg78") + "！");
                return;
            }
            if (!UInt32.TryParse(txtGlobalLimit.Text.Trim(), out ui32))
            {
                MsgErr(GetLanguage("Msg79") + "！");
                return;
            }
            var Msg80 = GetLanguage("Msg80");
            if (!Regex.IsMatch(txtDoor1Limit.Text.Trim(), reg))
            {
                MsgErr(string.Format(Msg80, 1));
                return;
            }
            if (!UInt32.TryParse(txtDoor1Limit.Text.Trim(), out ui32))
            {
                MsgErr($"1{GetLanguage("Msg80")}！");
                return;
            }

            if (!Regex.IsMatch(txtDoor2Limit.Text.Trim(), reg))
            {
                MsgErr(string.Format(Msg80, 2));
                return;
            }
            if (!UInt32.TryParse(txtDoor2Limit.Text.Trim(), out ui32))
            {
                MsgErr($"2{GetLanguage("Msg80")}！");
                return;
            }

            if (!Regex.IsMatch(txtDoor3Limit.Text.Trim(), reg))
            {
                MsgErr(string.Format(Msg80, 3));
                return;
            }
            if (!UInt32.TryParse(txtDoor3Limit.Text.Trim(), out ui32))
            {
                MsgErr($"3{GetLanguage("Msg80")}！");
                return;
            }

            if (!Regex.IsMatch(txtDoor4Limit.Text.Trim(), reg))
            {
                MsgErr(string.Format(Msg80, 4));
                return;
            }
            if (!UInt32.TryParse(txtDoor4Limit.Text.Trim(), out ui32))
            {
                MsgErr($"4{GetLanguage("Msg80")}！");
                return;
            }
            var Msg82 = GetLanguage("Msg82");
            if (!Regex.IsMatch(txtDoor1Enter.Text.Trim(), reg))
            {
                MsgErr(string.Format(Msg82, 1));
                return;
            }
            if (!UInt32.TryParse(txtDoor1Enter.Text.Trim(), out ui32))
            {
                MsgErr($"1{GetLanguage("Msg83")}！");
                return;
            }

            if (!Regex.IsMatch(txtDoor2Enter.Text.Trim(), reg))
            {
                MsgErr(string.Format(Msg82, 2));
                return;
            }
            if (!UInt32.TryParse(txtDoor2Enter.Text.Trim(), out ui32))
            {
                MsgErr($"2{GetLanguage("Msg83")}！");
                return;
            }

            if (!Regex.IsMatch(txtDoor3Enter.Text.Trim(), reg))
            {
                MsgErr(string.Format(Msg82, 3));
                return;
            }
            if (!UInt32.TryParse(txtDoor3Enter.Text.Trim(), out ui32))
            {
                MsgErr($"3{GetLanguage("Msg83")}！");
                return;
            }

            if (!Regex.IsMatch(txtDoor4Enter.Text.Trim(), reg))
            {
                MsgErr(string.Format(Msg82, 4));
                return;
            }
            if (!UInt32.TryParse(txtDoor4Enter.Text.Trim(), out ui32))
            {
                MsgErr($"4{GetLanguage("Msg83")}！");
                return;
            }


            DoorLimit dl = new DoorLimit();
            dl.GlobalLimit = Convert.ToUInt32(txtGlobalLimit.Text.Trim());
            dl.DoorLimitArray[0] = Convert.ToUInt32(txtDoor1Limit.Text.Trim());
            dl.DoorLimitArray[1] = Convert.ToUInt32(txtDoor2Limit.Text.Trim());
            dl.DoorLimitArray[2] = Convert.ToUInt32(txtDoor3Limit.Text.Trim());
            dl.DoorLimitArray[3] = Convert.ToUInt32(txtDoor4Limit.Text.Trim());

            dl.DoorEnterArray[0] = Convert.ToUInt32(txtDoor1Enter.Text.Trim());
            dl.DoorEnterArray[1] = Convert.ToUInt32(txtDoor2Enter.Text.Trim());
            dl.DoorEnterArray[2] = Convert.ToUInt32(txtDoor3Enter.Text.Trim());
            dl.DoorEnterArray[3] = Convert.ToUInt32(txtDoor4Enter.Text.Trim());

            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            WriteEnterDoorLimit cmd = new WriteEnterDoorLimit(cmdDtl, new WriteEnterDoorLimit_Parameter(dl));
            mMainForm.AddCommand(cmd);
        }
        #endregion

        #region 定时读卡播报语音消息参数
        private void BtnReadReadCardSpeak_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ReadReadCardSpeak cmd = new ReadReadCardSpeak(cmdDtl);
            mMainForm.AddCommand(cmd);

            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                ReadReadCardSpeak_Result result = cmde.Command.getResult() as ReadReadCardSpeak_Result;
                string UseStr = result.SpeakSetting.Use ? GetLanguage("Msg98") : GetLanguage("Msg97"); //定时读卡播报语音消息功能是否启用
                string MsgIndexStr = result.SpeakSetting.MsgIndex == 1 ? GetLanguage("Msg100") : GetLanguage("Msg101"); //消息编号类型
                string STime = result.SpeakSetting.BeginDate.ToString("yyyy-MM-dd HH");
                string ETime = result.SpeakSetting.EndDate.ToString("yyyy-MM-dd HH");
                Invoke(() =>
                {
                    if (result.SpeakSetting.Use)
                    {
                        rBtnEnableReadCardSpeak.Checked = true;
                    }
                    else
                    {
                        rBtnNoEnableReadCardSpeak.Checked = true;
                    }
                    if (result.SpeakSetting.MsgIndex == 1)
                    {
                        rBtnPayRent.Checked = true;
                    }
                    else
                    {
                        rBtnPayManagementFee.Checked = true;
                    }
                    txtSTime.Text = STime;
                    txtETime.Text = ETime;
                });
                var use = GetLanguage("label47");
                UseStr = use + UseStr + Environment.NewLine +
                            GetLanguage("label59") + MsgIndexStr + Environment.NewLine +
                         $"{GetLanguage("label61")}" + STime + Environment.NewLine +
                         use + ETime;
                mMainForm.AddCmdLog(cmde, UseStr);
            };
        }

        private void BtnWriteReadCardSpeak_Click(object sender, EventArgs e)
        {
            string reg = @"^\d{4}-\d{2}-\d{2} \d{2}" + GetLanguage("Msg105");
            if (!Regex.IsMatch(txtSTime.Text.Trim(), reg) || txtSTime.Text == "")
            {
                MsgErr(GetLanguage("Msg102") + "！");
                return;
            }
            if (Convert.ToInt16(txtSTime.Text.Substring(0, 4)) > 2099
                || Convert.ToInt16(txtSTime.Text.Substring(5, 2)) > 12
                || Convert.ToInt16(txtSTime.Text.Substring(8, 2)) > 31
                || Convert.ToInt16(txtSTime.Text.Substring(11, 2)) > 23)
            {
                MsgErr(GetLanguage("Msg102") + "！");
                return;
            }
            if (!Regex.IsMatch(txtETime.Text.Trim(), reg) || txtETime.Text == "")
            {
                MsgErr(GetLanguage("Msg103") + "！");
                return;
            }
            if (Convert.ToInt16(txtETime.Text.Substring(0, 4)) > 2099
                || Convert.ToInt16(txtETime.Text.Substring(5, 2)) > 12
                || Convert.ToInt16(txtETime.Text.Substring(8, 2)) > 31
                || Convert.ToInt16(txtETime.Text.Substring(11, 2)) > 23)
            {
                MsgErr(GetLanguage("Msg103") + "！");
                return;
            }
            if (Convert.ToInt16(txtSTime.Text.Substring(0, 4)) > Convert.ToInt16(txtETime.Text.Substring(0, 4)))
            {
                MsgErr(GetLanguage("Msg104") + "！");
                return;
            }
            else if (Convert.ToInt16(txtSTime.Text.Substring(0, 4)) == Convert.ToInt16(txtETime.Text.Substring(0, 4)))
            {
                if (Convert.ToInt16(txtSTime.Text.Substring(5, 2)) > Convert.ToInt16(txtETime.Text.Substring(5, 2)))
                {
                    MsgErr(GetLanguage("Msg104") + "！");
                    return;
                }
                else if (Convert.ToInt16(txtSTime.Text.Substring(5, 2)) == Convert.ToInt16(txtETime.Text.Substring(5, 2)))
                {
                    if (Convert.ToInt16(txtSTime.Text.Substring(8, 2)) > Convert.ToInt16(txtETime.Text.Substring(8, 2)))
                    {
                        MsgErr(GetLanguage("Msg104") + "！");
                        return;
                    }
                    else if (Convert.ToInt16(txtSTime.Text.Substring(8, 2)) == Convert.ToInt16(txtETime.Text.Substring(8, 2)))
                    {
                        if (Convert.ToInt16(txtSTime.Text.Substring(11, 2)) > Convert.ToInt16(txtETime.Text.Substring(11, 2)))
                        {
                            MsgErr(GetLanguage("Msg104") + "！");
                            return;
                        }
                    }
                }
            }

            int MsgIndex = 1;
            if (rBtnPayManagementFee.Checked == true)
            {
                MsgIndex = 2;
            }

            ReadCardSpeak rcs = new ReadCardSpeak();
            rcs.Use = rBtnEnableReadCardSpeak.Checked;
            rcs.MsgIndex = MsgIndex;
            var temp = GetLanguage("Msg105");
            rcs.BeginDate = Convert.ToDateTime(txtSTime.Text.Replace(temp, "") + ":00:00");
            rcs.EndDate = Convert.ToDateTime(txtETime.Text.Replace(temp, "") + ":00:00");

            //WriteReadCardSpeak_Parameter wp = new WriteReadCardSpeak_Parameter();
            //wp.SpeakSetting = rcs;
            //var buf = DotNetty.Buffers.UnpooledByteBufferAllocator.Default.Buffer(0x0A);
            //wp.GetBytes(buf);

            //WriteReadCardSpeak_Parameter wp2 = new WriteReadCardSpeak_Parameter();
            //wp2.SetBytes(buf);

            //string ReadCardSpeakInfo = "功能开关：" + wp2.SpeakSetting.Use +
            //                                 "  消息编号类型：" + wp2.SpeakSetting.MsgIndex +
            //                                 "  起始时段：" + wp2.SpeakSetting.BeginDate +
            //                                 "  功能开关：" + wp2.SpeakSetting.EndDate;
            //mMainForm.AddCmdLog(null, ReadCardSpeakInfo);

            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            WriteReadCardSpeak cmd = new WriteReadCardSpeak(cmdDtl, new WriteReadCardSpeak_Parameter(rcs));
            mMainForm.AddCommand(cmd);
        }
        #endregion

        #region 实时监控
        private void BtnBeginWatch_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            BeginWatch cmd = new BeginWatch(cmdDtl);
            mMainForm.AddCommand(cmd);
            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                mMainForm.AddCmdLog(cmde, GetLanguage("Msg106"));
            };
        }

        private void BtnCloseWatch_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            CloseWatch cmd = new CloseWatch(cmdDtl);
            mMainForm.AddCommand(cmd);
            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                mMainForm.AddCmdLog(cmde, GetLanguage("Msg107"));
            };
        }

        private void BtnReadWatchState_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ReadWatchState cmd = new ReadWatchState(cmdDtl);
            mMainForm.AddCommand(cmd);
            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                string ModeStr = cmd.WatchState == 0 ? GetLanguage("Msg108") : GetLanguage("Msg109"); //监控状态
                Invoke(() =>
                {
                    if (cmd.WatchState == 1)
                    {
                        lbWatchState.Text = GetLanguage("lbWatchState_2");
                        lbWatchState.ForeColor = Color.Green;
                    }
                    else
                    {
                        lbWatchState.Text = GetLanguage("lbWatchState_1");
                        lbWatchState.ForeColor = Color.Red;
                    }
                });
                mMainForm.AddCmdLog(cmde, ModeStr);
            };
        }
        #endregion

        #region 获取设备状态信息
        private void BtnWorkStatusInfo_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ReadWorkStatus cmd = new ReadWorkStatus(cmdDtl);
            mMainForm.AddCommand(cmd);

            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                ReadWorkStatus_Result result = cmde.Command.getResult() as ReadWorkStatus_Result;
                Invoke(() =>
                {
                    //继电器物理状态                    
                    mMainForm.AddCmdLog(cmde, GetRelayStateLog(result.RelayState));
                    //运行状态
                    mMainForm.AddCmdLog(cmde, GetDoorLongOpenStateLog(result.DoorLongOpenState));
                    //门磁开关
                    mMainForm.AddCmdLog(cmde, GetDoorStateLog(result.DoorState));
                    //门报警状态
                    mMainForm.AddCmdLog(cmde, GetDoorAlarmStateLog(result.DoorAlarmState));
                    //设备报警状态
                    mMainForm.AddCmdLog(cmde, GetAlarmStateLog(result.AlarmState));
                    //继电器逻辑状态
                    mMainForm.AddCmdLog(cmde, GetLockStateLog(result.LockState));
                    //锁定状态
                    mMainForm.AddCmdLog(cmde, GetPortLockStateLog(result.PortLockState));
                    //监控状态
                    mMainForm.AddCmdLog(cmde, GetWatchStateLog(result.WatchState));
                    //门内总人数
                    mMainForm.AddCmdLog(cmde, GetEnterTotalLog(result.EnterTotal));
                    //防盗主机布防状态
                    mMainForm.AddCmdLog(cmde, GetTheftStateLog(result.TheftState));
                });
            };
        }
        /// <summary>
        /// 继电器物理状态
        /// </summary>
        /// <param name="relayState"></param>
        /// <returns></returns>
        private string GetRelayStateLog(DoorPortDetail relayState)
        {
            string RelayState1Str = GetLanguage("Msg111");
            string RelayState2Str = GetLanguage("Msg112");
            string RelayState3Str = GetLanguage("Msg113");
            StringBuilder DoorInfo = new StringBuilder();
            for (int i = 0; i < relayState.DoorMax; i++)
            {
                if (relayState.DoorPort[i] == 0)
                {
                    this.dgvEquipmentStatusInfo.Rows[i].Cells[7].Value = RelayState1Str;
                    DoorInfo.AppendLine(GetLanguage("Door") + (i + 1) + GetLanguage("Msg126") + " ：" + RelayState1Str + "");
                }
                else if (relayState.DoorPort[i] == 1)
                {
                    this.dgvEquipmentStatusInfo.Rows[i].Cells[7].Value = RelayState2Str;
                    DoorInfo.AppendLine(GetLanguage("Door") + (i + 1) + GetLanguage("Msg126") + " ：" + RelayState1Str + "");
                }
                else if (relayState.DoorPort[i] == 2)
                {
                    this.dgvEquipmentStatusInfo.Rows[i].Cells[7].Value = RelayState3Str;
                    DoorInfo.AppendLine(GetLanguage("Door") + (i + 1) + GetLanguage("Msg126") + " ：" + RelayState1Str + "");
                }
            }
            return DoorInfo.ToString();
        }
        /// <summary>
        /// 运行状态
        /// </summary>
        /// <param name="doorLongOpenState"></param>
        /// <returns></returns>
        private string GetDoorLongOpenStateLog(DoorPortDetail doorLongOpenState)
        {
            string DoorLongOpenState1Str = GetLanguage("Msg114");
            string DoorLongOpenState2Str = GetLanguage("Msg115");
            var doorInfo = new StringBuilder();
            for (int i = 0; i < doorLongOpenState.DoorMax; i++)
            {
                if (doorLongOpenState.DoorPort[i] == 0)
                {
                    this.dgvEquipmentStatusInfo.Rows[i].Cells[1].Value = DoorLongOpenState1Str;
                    doorInfo.AppendLine(GetLanguage("Door") + (i + 1) + GetLanguage("Msg127") + " ：" + DoorLongOpenState1Str);
                }
                else if (doorLongOpenState.DoorPort[i] == 1)
                {
                    this.dgvEquipmentStatusInfo.Rows[i].Cells[1].Value = DoorLongOpenState2Str;
                    doorInfo.AppendLine(GetLanguage("Door") + (i + 1) + GetLanguage("Msg127") + " ：" + DoorLongOpenState2Str);
                }
            }
            return doorInfo.ToString();
        }
        /// <summary>
        /// 门磁开关
        /// </summary>
        /// <param name="DoorState"></param>
        /// <returns></returns>
        private string GetDoorStateLog(DoorPortDetail DoorState)
        {
            string DoorState1Str = GetLanguage("Msg117");
            string DoorState2Str = GetLanguage("Msg118");
            var doorInfo = new StringBuilder();
            for (int i = 0; i < DoorState.DoorMax; i++)
            {
                if (DoorState.DoorPort[i] == 0)
                {
                    this.dgvEquipmentStatusInfo.Rows[i].Cells[2].Value = DoorState1Str;
                    doorInfo.AppendLine(GetLanguage("Door") + (i + 1) + GetLanguage("Msg128") + " ：" + DoorState1Str);
                }
                else if (DoorState.DoorPort[i] == 1)
                {
                    this.dgvEquipmentStatusInfo.Rows[i].Cells[2].Value = DoorState2Str;
                    doorInfo.AppendLine(GetLanguage("Door") + (i + 1) + GetLanguage("Msg128") + "：" + DoorState2Str);
                }
            }
            return doorInfo.ToString();
        }
        /// <summary>
        /// 门报警状态
        /// </summary>
        /// <param name="doorAlarmState"></param>
        /// <returns></returns>
        private string GetDoorAlarmStateLog(DoorPortDetail doorAlarmState)
        {
            string DoorAlarmState1Str = GetLanguage("Msg116");
            string DoorAlarmState2Str = string.Empty;
            var doorInfo = new StringBuilder();
            for (int i = 0; i < doorAlarmState.DoorMax; i++)
            {
                if (doorAlarmState.DoorPort[i] == 0)
                {
                    this.dgvEquipmentStatusInfo.Rows[i].Cells[6].Value = DoorAlarmState1Str;
                    doorInfo.AppendLine("  " + GetLanguage("Door") + (i + 1) + GetLanguage("Msg129") + "：" + DoorAlarmState1Str);
                }
                else
                {
                    byte[] ByteDoorAlarmStateSet = new byte[] { doorAlarmState.DoorPort[i] };
                    BitArray bitSet = new BitArray(ByteDoorAlarmStateSet);
                    for (int j = 0; j < 6; j++)
                    {
                        if (bitSet[j])
                        {
                            if (j == 0)
                            {
                                DoorAlarmState2Str = DoorAlarmState2Str + "  " + GetLanguage("Msg11");
                            }
                            else if (j == 1)
                            {
                                DoorAlarmState2Str = DoorAlarmState2Str + "  " + GetLanguage("Msg130");
                            }
                            else if (j == 2)
                            {
                                DoorAlarmState2Str = DoorAlarmState2Str + "  " + GetLanguage("Msg131");
                            }
                            else if (j == 3)
                            {
                                DoorAlarmState2Str = DoorAlarmState2Str + "  " + GetLanguage("Msg132");
                            }
                            else if (j == 4)
                            {
                                DoorAlarmState2Str = DoorAlarmState2Str + "  " + GetLanguage("Msg133");
                            }
                            else if (j == 5)
                            {
                                DoorAlarmState2Str = DoorAlarmState2Str + "  " + GetLanguage("Msg134");
                            }
                        }
                    }
                    this.dgvEquipmentStatusInfo.Rows[i].Cells[6].Value = DoorAlarmState2Str;
                    doorInfo.AppendLine(GetLanguage("Door") + (i + 1) + GetLanguage("Msg129") + "：" + DoorAlarmState2Str);
                }
            }
            return doorInfo.ToString();
        }
        /// <summary>
        /// 设备报警状态
        /// </summary>
        /// <param name="AlarmState"></param>
        /// <returns></returns>
        private string GetAlarmStateLog(byte AlarmState)
        {
            string AlarmState1Str = GetLanguage("Msg119");
            string AlarmState2Str = GetLanguage("Msg120");
            var doorInfo = new StringBuilder();
            byte[] ByteSet = new byte[] { AlarmState };
            BitArray bit = new BitArray(ByteSet);
            for (int i = 0; i < 6; i++)
            {
                if (i == 0)
                {
                    if (bit[i])
                    {
                        this.dgvEquipmentStatusInfo.Rows[5].Cells[6].Value = AlarmState2Str;
                        doorInfo.AppendLine($"  {GetLanguage("Msg135")}：" + AlarmState2Str + "");
                    }
                    else
                    {
                        this.dgvEquipmentStatusInfo.Rows[5].Cells[6].Value = AlarmState1Str;
                        doorInfo.AppendLine($"  {GetLanguage("Msg135")}：" + AlarmState1Str + "");
                    }
                }
                if (i == 1)
                {
                    if (bit[i])
                    {
                        this.dgvEquipmentStatusInfo.Rows[7].Cells[6].Value = AlarmState2Str;
                        doorInfo.AppendLine($"  {GetLanguage("Msg136")}：" + AlarmState2Str + "");
                    }
                    else
                    {
                        this.dgvEquipmentStatusInfo.Rows[7].Cells[6].Value = AlarmState1Str;
                        doorInfo.AppendLine($"  {GetLanguage("Msg136")}：" + AlarmState1Str + "");
                    }
                }
                if (i == 2)
                {
                    if (bit[i])
                    {
                        this.dgvEquipmentStatusInfo.Rows[4].Cells[6].Value = AlarmState2Str;
                        doorInfo.AppendLine($"  {GetLanguage("Msg137")}：" + AlarmState2Str + "");
                    }
                    else
                    {
                        this.dgvEquipmentStatusInfo.Rows[4].Cells[6].Value = AlarmState1Str;
                        doorInfo.AppendLine($"  {GetLanguage("Msg137")}：" + AlarmState1Str + "");
                    }
                }
                if (i == 3)
                {
                    if (bit[i])
                    {
                        this.dgvEquipmentStatusInfo.Rows[6].Cells[6].Value = AlarmState2Str;
                        doorInfo.AppendLine($"{GetLanguage("Msg138")}：" + AlarmState2Str);
                    }
                    else
                    {
                        this.dgvEquipmentStatusInfo.Rows[6].Cells[6].Value = AlarmState1Str;
                        doorInfo.AppendLine($"{GetLanguage("Msg138")}：" + AlarmState1Str);
                    }
                }
                if (i == 5)
                {
                    if (bit[i])
                    {
                        this.dgvEquipmentStatusInfo.Rows[8].Cells[6].Value = AlarmState2Str;
                        doorInfo.AppendLine($"{GetLanguage("Msg139")}：" + AlarmState2Str);
                    }
                    else
                    {
                        this.dgvEquipmentStatusInfo.Rows[8].Cells[6].Value = AlarmState1Str;
                        doorInfo.AppendLine($"  {GetLanguage("Msg139")}：" + AlarmState1Str + "");
                    }
                }
            }
            return doorInfo.ToString();
        }
        /// <summary>
        /// 继电器逻辑状态
        /// </summary>
        /// <param name="lockState"></param>
        /// <returns></returns>
        private string GetLockStateLog(DoorPortDetail lockState)
        {
            string LockState1Str = GetLanguage("Msg121");
            string LockState2Str = GetLanguage("Msg122");
            string LockState3Str = GetLanguage("Msg123");
            var doorInfo = new StringBuilder();
            for (int i = 0; i < 8; i++)
            {
                if (i < 4)
                {
                    if (lockState.DoorPort[i] == 0)
                    {
                        this.dgvEquipmentStatusInfo.Rows[i].Cells[3].Value = LockState1Str;
                        doorInfo.AppendLine($"{GetLanguage("Door")}" + (i + 1) + $"{GetLanguage("Msg140")}：" + LockState1Str);
                    }
                    else if (lockState.DoorPort[i] == 1)
                    {
                        this.dgvEquipmentStatusInfo.Rows[i].Cells[3].Value = LockState2Str;
                        doorInfo.AppendLine($"{GetLanguage("Door")}" + (i + 1) + $"{GetLanguage("Msg140")}：" + LockState2Str);
                    }
                    else if (lockState.DoorPort[i] == 2)
                    {
                        this.dgvEquipmentStatusInfo.Rows[i].Cells[3].Value = LockState3Str;
                        doorInfo.AppendLine($"{GetLanguage("Door")}" + (i + 1) + $"{GetLanguage("Msg140")}：" + LockState3Str);
                    }
                }
                else if (i == 4)
                {
                    this.dgvEquipmentStatusInfo.Rows[i].Cells[3].Value = LockState1Str;
                    doorInfo.AppendLine($"{GetLanguage("Msg141")}：" + LockState1Str + "");
                }
                else if (i == 5)
                {
                    this.dgvEquipmentStatusInfo.Rows[i].Cells[3].Value = LockState1Str;
                    doorInfo.AppendLine($"{GetLanguage("Msg142")}：" + LockState1Str + "");
                }
                else if (i == 6)
                {
                    this.dgvEquipmentStatusInfo.Rows[i].Cells[3].Value = LockState1Str;
                    doorInfo.AppendLine($"{GetLanguage("Msg143")}：" + LockState1Str + "");
                }
                else if (i == 7)
                {
                    this.dgvEquipmentStatusInfo.Rows[i].Cells[3].Value = LockState1Str;
                    doorInfo.AppendLine($"{GetLanguage("Msg144")}：" + LockState1Str + "");
                }
            }
            return doorInfo.ToString();
        }

        /// <summary>
        /// 锁定状态
        /// </summary>
        /// <param name="PortLockState"></param>
        /// <returns></returns>
        private string GetPortLockStateLog(DoorPortDetail PortLockState)
        {
            string PortLockState1Str = GetLanguage("Msg124");
            string PortLockState2Str = GetLanguage("Msg125");
            var DoorInfo = new StringBuilder();
            for (int i = 0; i < PortLockState.DoorMax; i++)
            {
                if (PortLockState.DoorPort[i] == 0)
                {
                    this.dgvEquipmentStatusInfo.Rows[i].Cells[4].Value = PortLockState1Str;
                    DoorInfo.AppendLine($"{GetLanguage("Door")}" + (i + 1) + $"  {GetLanguage("Msg145")}：" + PortLockState1Str);
                }
                else if (PortLockState.DoorPort[i] == 1)
                {
                    this.dgvEquipmentStatusInfo.Rows[i].Cells[4].Value = PortLockState2Str;
                    DoorInfo.AppendLine($"{GetLanguage("Door")}" + (i + 1) + $"  {GetLanguage("Msg145")}：" + PortLockState2Str);
                }
            }
            return DoorInfo.ToString();
        }
        /// <summary>
        /// 监控状态
        /// </summary>
        /// <param name="WatchState"></param>
        /// <returns></returns>
        private string GetWatchStateLog(byte WatchState)
        {
            if (WatchState == 1)
            {
                lbSWatchState.Text = GetLanguage("lbWatchState_2");
                lbSWatchState.ForeColor = Color.Green;
                return $"{GetLanguage("Lab_WatchStatus")}{GetLanguage("lbWatchState_2")}" + Environment.NewLine;
            }
            else
            {
                lbSWatchState.Text = GetLanguage("lbWatchState_1");
                lbSWatchState.ForeColor = Color.Red;
                return $"{GetLanguage("Lab_WatchStatus")}{GetLanguage("lbWatchState_1")}" + Environment.NewLine;
            }
        }
        /// <summary>
        /// 门内总人数
        /// </summary>
        /// <param name="EnterTotal"></param>
        /// <returns></returns>
        private string GetEnterTotalLog(DoorLimit EnterTotal)
        {
            var DoorInfo = new StringBuilder();
            this.txtAllNum.Text = EnterTotal.GlobalEnter.ToString();
            var doorenter = GetLanguage("Msg147");
            DoorInfo.AppendLine($"{GetLanguage("Msg146")}" + EnterTotal.DoorEnterArray[0].ToString());
            this.dgvEquipmentStatusInfo.Rows[0].Cells[5].Value = EnterTotal.DoorEnterArray[0].ToString(); //门1人数
            DoorInfo.AppendLine($"{string.Format(doorenter, 1)}：" + EnterTotal.DoorEnterArray[0].ToString());
            this.dgvEquipmentStatusInfo.Rows[1].Cells[5].Value = EnterTotal.DoorEnterArray[1].ToString(); //门2人数
            DoorInfo.AppendLine($"{string.Format(doorenter, 2)}：" + EnterTotal.DoorEnterArray[1].ToString());
            this.dgvEquipmentStatusInfo.Rows[2].Cells[5].Value = EnterTotal.DoorEnterArray[2].ToString(); //门3人数
            DoorInfo.AppendLine($"{string.Format(doorenter, 3)}：" + EnterTotal.DoorEnterArray[2].ToString());
            this.dgvEquipmentStatusInfo.Rows[3].Cells[5].Value = EnterTotal.DoorEnterArray[3].ToString(); //门4人数
            DoorInfo.AppendLine($"{string.Format(doorenter, 4)}：" + EnterTotal.DoorEnterArray[3].ToString());
            return DoorInfo.ToString();
        }
        static string[] TheftStateArray = new string[] { string.Empty, "Msg148", "Msg149", "Msg150", "Msg151", "Msg152", "Msg153" };
        /// <summary>
        /// 防盗主机布防状态
        /// </summary>
        /// <param name="TheftState"></param>
        /// <returns></returns>
        private string GetTheftStateLog(byte TheftState)
        {
            string TheftStateStr = string.Empty;
            if (TheftState != 0)
            {
                TheftStateStr = GetLanguage(TheftStateArray[TheftState]);
            }
            return $"{GetLanguage("Msg154")}：" + TheftStateStr + Environment.NewLine;
        }
        #endregion

        #region 初始化设备
        private void BtnInitalData_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            cmdDtl.Timeout = 100000;
            FormatController cmd = new FormatController(cmdDtl);
            mMainForm.AddCommand(cmd);
            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                mMainForm.AddCmdLog(cmde, GetLanguage("Msg155") + "！");
            };
        }
        #endregion

        #region 缓存区操作
        private void BtnReadCacheContent_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ReadCacheContent cmd = new ReadCacheContent(cmdDtl);
            mMainForm.AddCommand(cmd);

            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                CacheContent_Result result = cmde.Command.getResult() as CacheContent_Result;
                string CacheContent = result.CacheContent;
                Invoke(() =>
                {
                    txtCacheContent.Text = CacheContent;
                });
                CacheContent = GetLanguage("Lab_CacheContent") + "：" + CacheContent;
                mMainForm.AddCmdLog(cmde, CacheContent);
            };
        }

        private void BtnWriteCacheContent_Click(object sender, EventArgs e)
        {
            string reg = @"^\+?[0-9]*$";
            if (!Regex.IsMatch(txtCacheContent.Text.Trim(), reg) || txtCacheContent.Text.Trim().Length > 30 || string.IsNullOrEmpty(txtCacheContent.Text.Trim()))
            {
                MsgErr(GetLanguage("Msg156") + "！");
                return;
            }
            string cacheContent = txtCacheContent.Text.Trim();

            //CacheContent_Parameter wp = new CacheContent_Parameter();
            //wp.CacheContent = cacheContent;
            //var buf = DotNetty.Buffers.UnpooledByteBufferAllocator.Default.Buffer(0x1E);
            //wp.GetBytes(buf);

            //CacheContent_Parameter wp2 = new CacheContent_Parameter();
            //wp2.SetBytes(buf);

            //cacheContent = "缓存区内容：" + cacheContent;
            //mMainForm.AddCmdLog(null, cacheContent);

            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            WriteCacheContent cmd = new WriteCacheContent(cmdDtl, new CacheContent_Parameter(cacheContent));
            mMainForm.AddCommand(cmd);
        }
        #endregion

        #region 客户端控制器保活间隔
        private void BtnReadKeepAliveInterval_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ReadKeepAliveInterval cmd = new ReadKeepAliveInterval(cmdDtl);
            mMainForm.AddCommand(cmd);

            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                ReadKeepAliveInterval_Result result = cmde.Command.getResult() as ReadKeepAliveInterval_Result;

                ushort IntervalTime = result.IntervalTime; //保活间隔时间
                string IntervalTimeInfo = string.Empty;
                var temp = GetLanguage("Msg13");
                if (IntervalTime == 0)
                {
                    IntervalTimeInfo = GetLanguage("Msg157");
                }
                else
                {
                    IntervalTimeInfo = IntervalTime.ToString();
                }

                Invoke(() =>
                {
                    cbxKeepAliveInterval.Text = IntervalTimeInfo.Replace(temp, "");
                });
                string IntervalTimeStr = GetLanguage("Lab_KeepAliveInterval1") + "：" + IntervalTimeInfo + GetLanguage("Lab_KeepAliveInterval2");
                mMainForm.AddCmdLog(cmde, IntervalTimeStr);
            };
        }

        private void BtnWriteKeepAliveInterval_Click(object sender, EventArgs e)
        {
            string reg = @"^\+?[0-9]*$";
            if (!Regex.IsMatch(cbxKeepAliveInterval.Text.Trim(), reg))
            {
                if (cbxKeepAliveInterval.Text != GetLanguage("Msg157"))
                {
                    MsgErr(GetLanguage("Msg158") + "！");
                    return;
                }
            }
            if (Regex.IsMatch(cbxKeepAliveInterval.Text.Trim(), reg))
            {
                if (Convert.ToUInt32(cbxKeepAliveInterval.Text) < 0 || Convert.ToUInt32(cbxKeepAliveInterval.Text) > 65535)
                {
                    MsgErr(GetLanguage("Msg158") + "！");
                    return;
                }
            }

            ushort IntervalTime = 0;
            string deadlineInfo = cbxKeepAliveInterval.Text;
            if (deadlineInfo == GetLanguage("Msg157"))
            {
                IntervalTime = 0;
            }
            else
            {
                IntervalTime = Convert.ToUInt16(cbxKeepAliveInterval.Text);
            }

            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            WriteKeepAliveInterval cmd = new WriteKeepAliveInterval(cmdDtl, new WriteKeepAliveInterval_Parameter(IntervalTime));
            mMainForm.AddCommand(cmd);
        }
        #endregion

        #region 防探测功能
        private void BtnReadExploreLockMode_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ReadExploreLockMode cmd = new ReadExploreLockMode(cmdDtl);
            mMainForm.AddCommand(cmd);

            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                ReadExploreLockMode_Result result = cmde.Command.getResult() as ReadExploreLockMode_Result;
                string ModeStr = result.Use == 0 ? GetLanguage("Msg159") : GetLanguage("Msg160"); //防探测功能是否启用
                Invoke(() =>
                {
                    if (result.Use == 0)
                    {
                        rBtnNoExploreLockMode.Checked = true;
                    }
                    else
                    {
                        rBtnExploreLockMode.Checked = true;
                    }
                });
                ModeStr = GetLanguage("Msg167") + "：" + ModeStr;
                mMainForm.AddCmdLog(cmde, ModeStr);
            };
        }

        private void BtnWriteExploreLockMode_Click(object sender, EventArgs e)
        {
            byte use = 0;
            if (rBtnExploreLockMode.Checked == true)
            {
                use = 1;
            }

            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            WriteExploreLockMode cmd = new WriteExploreLockMode(cmdDtl, new WriteExploreLockMode_Parameter(use));
            mMainForm.AddCommand(cmd);
        }
        #endregion

        #region 485线路反接检测开关
        private void BtnReadCheck485Line_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ReadCheck485Line cmd = new ReadCheck485Line(cmdDtl);
            mMainForm.AddCommand(cmd);

            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                ReadCheck485Line_Result result = cmde.Command.getResult() as ReadCheck485Line_Result;
                string ModeStr = result.Use == 0 ? GetLanguage("Msg159") : GetLanguage("Msg160"); //485线路反接检测开关是否启用
                Invoke(() =>
                {
                    if (result.Use == 0)
                    {
                        rBtnNoCheck485Line.Checked = true;
                    }
                    else
                    {
                        rBtnCheck485Line.Checked = true;
                    }
                });
                ModeStr = GetLanguage("groupBox15") + "：" + ModeStr;
                mMainForm.AddCmdLog(cmde, ModeStr);
            };
        }

        private void BtnWriteCheck485Line_Click(object sender, EventArgs e)
        {
            byte use = 0;
            if (rBtnCheck485Line.Checked == true)
            {
                use = 1;
            }

            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            WriteCheck485Line cmd = new WriteCheck485Line(cmdDtl, new WriteCheck485Line_Parameter(use));
            mMainForm.AddCommand(cmd);
        }
        #endregion

        #region TCP客户端操作
        private void BtnReadTCPClientList_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ReadTCPClientList cmd = new ReadTCPClientList(cmdDtl);
            mMainForm.AddCommand(cmd);
            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                Invoke(() =>
                {
                    TCPClient_Result result = cmde.Command.getResult() as TCPClient_Result;
                    this.dgvTCPClientList.AllowUserToAddRows = false;
                    this.dgvTCPClientList.Rows.Clear();
                    if (result.tCPClientDetail.TCPClientNum > 0)
                    {
                        this.dgvTCPClientList.Rows.Add(result.tCPClientDetail.TCPClientNum);
                    }
                    for (int i = 0; i < result.tCPClientDetail.TCPClientNum; i++)
                    {
                        this.dgvTCPClientList.Rows[i].Cells[1].Value = i + 1;
                        this.dgvTCPClientList.Rows[i].Cells[2].Value = result.tCPClientDetail.IP[i];
                        this.dgvTCPClientList.Rows[i].Cells[3].Value = result.tCPClientDetail.TCPPort[i];
                        if (result.tCPClientDetail.ConnectTime[i].Year != 1)
                        {
                            this.dgvTCPClientList.Rows[i].Cells[4].Value = result.tCPClientDetail.ConnectTime[i];
                        }
                    }
                    mMainForm.AddCmdLog(cmde, GetLanguage("Msg162") + "：" + result.tCPClientDetail.TCPClientNum);
                });
            };
        }

        private void BtnStopTCPClientConnection_Click(object sender, EventArgs e)
        {
            TCPClientDetail tCPClientDetail = new TCPClientDetail();
            if (this.dgvTCPClientList.Rows.Count > 0)
            {
                tCPClientDetail.IP = new string[this.dgvTCPClientList.Rows.Count];
                tCPClientDetail.TCPPort = new ushort[this.dgvTCPClientList.Rows.Count];
                for (int i = 0; i < this.dgvTCPClientList.Rows.Count; i++)
                {
                    if (Convert.ToBoolean(this.dgvTCPClientList.Rows[i].Cells[0].EditedFormattedValue))
                    {
                        tCPClientDetail.IP[0] = this.dgvTCPClientList.Rows[i].Cells[2].Value.ToString();
                        tCPClientDetail.TCPPort[0] = Convert.ToUInt16(this.dgvTCPClientList.Rows[i].Cells[3].Value);
                        break;
                    }
                }
                if (string.IsNullOrEmpty(tCPClientDetail.IP[0])) //没有选择，默认选择列表第一条数据进行断开连接
                {
                    tCPClientDetail.IP[0] = this.dgvTCPClientList.Rows[0].Cells[2].Value.ToString();
                    tCPClientDetail.TCPPort[0] = Convert.ToUInt16(this.dgvTCPClientList.Rows[0].Cells[3].Value);
                }
            }
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            StopTCPClientConnection cmd = new StopTCPClientConnection(cmdDtl, new TCPClient_Parameter(tCPClientDetail));
            mMainForm.AddCommand(cmd);

            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                Invoke(() =>
                {
                    string TCPClientInfo = "IP：" + tCPClientDetail.IP[0] +
                                           $" {GetLanguage("Msg163")}：" + tCPClientDetail.TCPPort[0];
                    mMainForm.AddCmdLog(cmde, TCPClientInfo);
                });
            };
        }

        private void BtnStopAllTCPClientConnection_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            //cmdDtl.Timeout = 5000;
            if (cmdDtl == null) return;
            StopAllTCPClientConnection cmd = new StopAllTCPClientConnection(cmdDtl);
            mMainForm.AddCommand(cmd);
            //处理返回值          
        }
        #endregion

        #region 有效期即将过期提醒时间
        private void BtnReadCardDeadlineTipDay_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ReadCardDeadlineTipDay cmd = new ReadCardDeadlineTipDay(cmdDtl);
            mMainForm.AddCommand(cmd);

            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                ReadCardDeadlineTipDay_Result result = cmde.Command.getResult() as ReadCardDeadlineTipDay_Result;
                string TipDayInfo = string.Empty;
                Invoke(() =>
                {
                    cbxCardDeadlineTipDay.Text = result.Day == 0 ? GetLanguage("Msg157") : "" + result.Day + "";
                });
                if (result.Day == 0)
                {
                    TipDayInfo = GetLanguage("Msg165");
                }
                else
                {
                    TipDayInfo = GetLanguage("Msg168") + "：" + result.Day + GetLanguage("Msg169");
                }
                mMainForm.AddCmdLog(cmde, TipDayInfo);
            };
        }

        private void BtnWriteCardDeadlineTipDay_Click(object sender, EventArgs e)
        {
            string reg = @"^\+?[0-9]*$";
            if (!Regex.IsMatch(cbxCardDeadlineTipDay.Text.Trim(), reg) || string.IsNullOrEmpty(cbxCardDeadlineTipDay.Text.Trim()))
            {
                if (cbxCardDeadlineTipDay.Text != GetLanguage("Msg157"))
                {
                    MsgErr(GetLanguage("Msg166") + "！");
                    return;
                }
            }
            if (Regex.IsMatch(cbxCardDeadlineTipDay.Text.Trim(), reg))
            {
                if (Convert.ToUInt32(cbxCardDeadlineTipDay.Text) < 0 || Convert.ToUInt32(cbxCardDeadlineTipDay.Text) > 255)
                {
                    MsgErr(GetLanguage("Msg166") + "！");
                    return;
                }
            }

            byte tipDay = 0;
            string tipDayInfo = cbxCardDeadlineTipDay.Text;
            if (tipDayInfo == GetLanguage("Msg157"))
            {
                tipDay = 0;
            }
            else
            {
                tipDay = Convert.ToByte(tipDayInfo);
            }

            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            WriteCardDeadlineTipDay cmd = new WriteCardDeadlineTipDay(cmdDtl, new WriteCardDeadlineTipDay_Parameter(tipDay));
            mMainForm.AddCommand(cmd);
        }
        #endregion

        #region HTTP网页登陆开关
        private void BtnReadHTTPPageLandingSwitch_Click(object sender, EventArgs e)
        {
            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            ReadHTTPPageLandingSwitch cmd = new ReadHTTPPageLandingSwitch(cmdDtl);
            mMainForm.AddCommand(cmd);

            //处理返回值
            cmdDtl.CommandCompleteEvent += (sdr, cmde) =>
            {
                ReadHTTPPageLandingSwitch_Result result = cmde.Command.getResult() as ReadHTTPPageLandingSwitch_Result;
                string ModeStr = result.Use == 0 ? GetLanguage("Msg159") : GetLanguage("Msg160"); //HTTP网页登陆开关是否启用
                Invoke(() =>
                {
                    if (result.Use == 0)
                    {
                        rBtnNoHTTPPageLandingSwitch.Checked = true;
                    }
                    else
                    {
                        rBtnHTTPPageLandingSwitch.Checked = true;
                    }
                });
                mMainForm.AddCmdLog(cmde, ModeStr);
            };
        }

        private void BtnWriteHTTPPageLandingSwitch_Click(object sender, EventArgs e)
        {
            byte use = 0;
            if (rBtnHTTPPageLandingSwitch.Checked == true)
            {
                use = 1;
            }

            var cmdDtl = mMainForm.GetCommandDetail();
            if (cmdDtl == null) return;
            WriteHTTPPageLandingSwitch cmd = new WriteHTTPPageLandingSwitch(cmdDtl, new WriteHTTPPageLandingSwitch_Parameter(use));
            mMainForm.AddCommand(cmd);
        }
        #endregion

    }
}
